<template>
  <div class="main-content pd16">

    <!--搜索栏-->
    <el-form class="search-form" ref="searchFormRef" :model="searchForm" :inline="true" label-width="70">

      <el-form-item label="任务名称" prop="name" label-width="70">
        <el-input v-model="searchForm.name" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item label="任务描述" prop="remark" label-width="70">
        <el-input v-model="searchForm.remark" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item v-if="option.isJw" label="状态" prop="isOpen" label-width="40">
        <el-select v-model="searchForm.isOpen" placeholder="请选择" clearable style="width: 120px">
          <el-option v-for="dict in enu_jw_task" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="起止时间" prop="time" label-width="70">
        <el-date-picker
            v-model="searchForm.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="searchData">搜索</el-button>
        <el-button icon="Refresh" @click="resetSearch">重置</el-button>
      </el-form-item>

    </el-form>

    <!--按钮组-->
    <div class="fx mgb12" v-if="option.isJw">
      <el-button type="primary" plain size="small" icon="Plus" @click="openAdd">新增任务</el-button>
      <el-button plain size="small" icon="Unlock" @click="openBatch">批量开启</el-button>
      <el-button type="warning" plain size="small" icon="Lock" @click="closeBatch">批量关闭</el-button>
      <el-button type="danger" plain size="small" icon="Delete" @click="deleteBatch">批量删除</el-button>
      <el-button plain size="small" icon="Setting" @click="openZipManage">压缩包管理</el-button>
      <el-button type="primary" plain size="small" icon="Files" @click="createZipBatch">批量生成压缩包</el-button>
    </div>

    <!--表格-->
    <el-table border highlight-current-row row-key="id" v-loading="option.loading" :data="option.tableData"
              @selection-change="selectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="任务类型" :show-overflow-tooltip="true" align="center" width="110">
        <template #default="scope">
          <el-tag v-if="route.query.type=='0'" type="success" style="font-size: 15px">教师任务</el-tag>
          <el-tag v-if="route.query.type=='1'" style="font-size: 15px">部门任务</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="任务名称" prop="name" :show-overflow-tooltip="true" align="center"></el-table-column>
      <el-table-column label="任务描述" prop="remark" :show-overflow-tooltip="true" align="center"></el-table-column>
      <el-table-column label="状态" prop="isOpen" align="center" :show-overflow-tooltip="true" width="120">
        <template #default="scope">
          <dict-tag :options="enu_jw_task" :value="scope.row.isOpen"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间-截止时间" prop="startTime" :show-overflow-tooltip="true" align="center"
                       width="350">
        <template #default="scope">
          {{ scope.row.startTime + ' 至 ' + scope.row.endTime }}
        </template>
      </el-table-column>

      <el-table-column label="创建时间" prop="ct" :show-overflow-tooltip="true" align="center"
                       width="170"></el-table-column>

      <el-table-column label="修改时间" prop="ut" :show-overflow-tooltip="true" align="center"
                       width="170"></el-table-column>

      <el-table-column label="操作" align="center" fixed="right" :min-width="(option.isJs || option.isBm)?150:150">
        <template #default="scope">
          <div class="fx_center_center fx_wrap">
            <el-upload
                v-if="option.isBm || option.isJs"
                class="fx_center_center"
                style="margin-right: 10px"
                :ref="'uploadRef'+scope.$index"
                :action="option.uploadUrl"
                :show-file-list="false"
                :headers="{token:getAccessToken()}"
                :data="fileData"
                :on-change="uploadChange"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :on-progress="uploadProgress"
                :auto-upload="false"
            >
              <template #trigger>
                <el-button link type="primary" icon="UploadFilled" @click="setFileData(scope.row,scope.$index)">
                  上传资料
                </el-button>
              </template>
            </el-upload>

            <!--教务处允许编辑-->
            <el-button v-if="option.isJw"
                       link type="primary" icon="Edit" @click="openEdit(scope.row)">
              编辑
            </el-button>

            <el-button link type="primary" icon="Files" @click="openFiles(scope.row)">
              资料管理
            </el-button>

            <!--教务处允打包下载-->
            <!--            <el-button v-if="option.isJw"-->
            <!--                       link type="primary" icon="Files" @click="createZip(scope.row)">-->
            <!--              生成压缩包-->
            <!--            </el-button>-->

            <!--            <el-button v-if="option.isJw"-->
            <!--                       link type="primary" icon="Setting" @click="openZipManage(scope.row)">-->
            <!--              压缩包管理-->
            <!--            </el-button>-->

          </div>

        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="fx_end">
      <el-pagination
          class="mgt8"
          small
          background
          :total="option.totalRow"
          :page-sizes="option.pageSizes"
          v-model:current-page="searchForm.pageNumber"
          v-model:page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="searchData"
          @current-change="searchData"
      />
    </div>

    <!--Dialog-->
    <el-dialog :title="option.dialogTitle" v-model="option.openDialog" width="680" :close-on-click-modal="false"
               draggable append-to-body destroy-on-close>

      <el-form ref="formDataRef" size="default" :model="formData" :rules="formRules" label-width="200">

        <el-form-item label="任务名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" style="width: 300px"/>
        </el-form-item>

        <el-form-item label="状态" prop="isOpen">
          <el-select v-model="formData.isOpen" placeholder="请选择" clearable style="width: 300px">
            <el-option v-for="dict in enu_jw_task" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
              style="width: 300px"
              v-model="formData.startTime"
              type="datetime"
              placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker
              style="width: 300px"
              v-model="formData.endTime"
              type="datetime"
              placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="任务描述" prop="remark">
          <el-input v-model="formData.remark" type="textarea" maxlength="200" placeholder="请输入"
                    show-word-limit :autosize="{ minRows: 2, maxRows: 6 }" style="width: 300px"/>
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="()=>{option.openDialog=false}">取 消</el-button>
        <el-button v-if="option.dialogType==='add'" type="primary" @click="submitAdd">确 定</el-button>
        <el-button v-if="option.dialogType==='edit'" type="primary" @click="submitEdit">保 存</el-button>
      </template>

    </el-dialog>

    <!--Dialog-->
    <el-dialog :title="option.dialogFileTitle" v-model="option.openFileDialog" width="70%" :close-on-click-modal="false"
               draggable append-to-body destroy-on-close>
      <jw-teacher-task-res-files
          :taskId="option.taskId"
          :client="option.client"
          :is-jw="option.isJw"
          :is-bm="option.isBm"
          :is-js="option.isJs"
          :kcNumber="option.kcNumber"
          :jsNumber="option.jsNumber">
      </jw-teacher-task-res-files>
    </el-dialog>

    <!--Dialog-->
    <el-dialog :title="option.dialogTitleZip" v-model="option.openDialogZip" width="80%" :close-on-click-modal="false"
               draggable append-to-body destroy-on-close>
      <zip-file-list
          :client="option.client"
          :is-jw="option.isJw"
          :is-bm="option.isBm"
          :is-js="option.isJs">
      </zip-file-list>
    </el-dialog>

    <!--上传进度-->
    <el-dialog :title="option.dialogTitleUp" v-model="option.openDialogUp" width="600" :close-on-click-modal="false"
               draggable append-to-body destroy-on-close :show-close="false">
      <div class="fx_center_center fx_col">
        <div style="color:red;line-height: 30px;font-size: 15px">
          注意：文件上传过程中不要关闭上传页面，上传速度由您的网速决定。
        </div>
        <div style="color:red;line-height: 30px;font-size: 15px;margin-bottom: 15px">
          注意：文件上传后，需要时间保存文件记录，请不要关闭页面。
        </div>
        <el-progress type="circle" :percentage="option.uploadProgress" status="success">
          <template #default="{ percentage }">
            <span class="percentage-value">{{ percentage }}%</span>
            <br>
            <span class="percentage-label">文件上传进度</span>
          </template>
        </el-progress>

      </div>

    </el-dialog>

  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, ref} from "vue";
import $modal from "@/common/utils/modal";
import {closeLoading, copyNew, loading, trimStr} from "@/common/utils/kit";
import {asDict} from "@/api/common";
import {dateToStr} from "@/common/utils/date";
import {
  bmPageTask,
  jsPageTask,
  jwAddTask,
  jwCreateTaskZip,
  jwDelTask,
  jwDownloadZip,
  jwPageTask,
  jwUpdateTask,
  jwUpdateTaskStatus
} from "@/api/jldz";
import DictTag from "@/common/component/DictTag.vue";
import {useRoute} from "vue-router "
import router from "@/common/router";
import {getAccessToken} from "@/common/utils/cache";
import JwTeacherTaskResFiles from "@/module/jldz/fileList.vue";
import ZipFileList from "@/module/jldz/zipFileList.vue";
import {ElMessageBox} from "element-plus";
import $event from "@/common/utils/event";

//文件：上传参数
const fileData = ref({});

//文件：上传进度/保存进度
function uploadProgress(evt, uploadFile, uploadFiles) {
  option.value.uploadProgress = Math.floor(evt.percent)
  //
  if (option.value.uploadProgress >= 100) {
    loading("正在保存文件，不要关闭页面，请耐心等待...")
  }
}

//文件：设置上传参数
function setFileData(row, $index) {
  console.log(row)
  if (option.value.isJs) {
    //活动编号
    fileData.value.taskId = row.id
    //教师任务0；部门任务1；非任务2；
    fileData.value.taskType = '0'
  }

  if (option.value.isBm) {
    //活动编号
    fileData.value.taskId = row.id
    //教师任务0；部门任务1；非任务2；
    fileData.value.taskType = '1'
  }

  // 指定当前打开的上文组件Ref
  fileData.value.$fileRefIndex = $index
  console.log(fileData.value)
}

//文件：状态变动
function uploadChange(file, files) {
  if (file.size * 1 > 1024 * 1024 * 1024 * 2) {
    $modal.error(file.name + " 上传失败：文件最大支持 2G", 4000);
    return;
  }

  if (file && file.status === 'ready') {
    console.log("开始上传文件  file ----->", JSON.stringify(file))
    console.log("开始上传文件  fileData ----->", JSON.stringify(fileData.value))
    option.value.uploadProgress = 0;
    option.value.fileSaveProgress = 0;
    option.value.dialogTitleUp = "文件正在上传中，请不要关闭当前页面"
    option.value.openDialogUp = true;
    proxy.$refs["uploadRef" + fileData.value.$fileRefIndex].submit()
  }
}

//文件：上传成功
function uploadSuccess(res, file, files) {
  option.value.openDialogUp = false;
  console.log("uploadSuccess  res  file  files", res, file, files)
  if (res.success) {
    $modal.success(file.name + " 上传成功");
  } else {
    $modal.error(file.name + " 上传失败：" + res.message, 4000);
  }
  closeLoading()
}

//文件：上传失败
function uploadError(res, file, files) {
  option.value.openDialogUp = false;
  console.log("uploadError  res  file  files", res, file, files)
  $modal.error(file.name + " 上传失败：" + res.message, 4000);
  closeLoading()
}


const {proxy} = getCurrentInstance();

const route = useRoute();
const routeParam = useRoute().query;

const {enu_jw_task} = asDict("enu_jw_task");

let optionKey = {
  loading: false,
  openDialog: false,
  dialogTitle: "",
  dialogType: "",
  openDialogZip: false,
  dialogTitleZip: "",
  dialogTypeZip: "",
  dialogTitleUp: "",
  openDialogUp: false,
  tableData: [],
  selectIds: [],
  selectNames: [],
  pageSizes: [50, 100, 500, 1000, 2000, 5000],
  totalRow: 0,
  nowRoleId: 0,
  defaultChecked: [],
  allRole: [],
  type: '',
  client: '',//当前菜单
  isJw: false,//是否是教务处
  isBm: false,//是否是部门
  isJs: false,//是否是教师
  dialogFileTitle: '',
  openFileDialog: false,
  uploadUrl: import.meta.env.VITE_UPLOAD_URL + '/manage/jldz/uploadFile',
  uploadProgress: 0
}

let searchKey = {
  pageNumber: 1,
  pageSize: 100,
  time: '',
  name: '',
  remark: '',
  type: '0',
  isOpen: '',
}
let formKey = {
  name: "",//
  sort: 100,//
  remark: "",//
  isOpen: "",//
  startTime: "",//
  endTime: "",//
}

const formRules = ref({
  name: [{required: true, message: "不能为空", trigger: "blur"}],
  isOpen: [{required: true, message: "不能为空", trigger: "change"}],
  startTime: [{required: true, message: "不能为空", trigger: "blur"}],
  endTime: [{required: true, message: "不能为空", trigger: "blur"}],
  isInMute: [{required: true, message: "不能为空", trigger: "blur"}],
  closeSettingTime: [{required: true, message: "不能为空", trigger: "blur"}],
});

const searchForm = ref(searchKey)
const formData = ref(formKey);
const option = ref(optionKey);

function resetForm() {
  formData.value = copyNew(formKey);
}

function resetSearch() {
  proxy.$refs["searchFormRef"].resetFields();
  searchData()
}

//页面加载完成回调
onMounted(() => {
  option.value.client = routeParam.client
  option.value.isJw = routeParam.client === 'jwBmTask' || routeParam.client === 'jwTeacherTask' || routeParam.client === 'jwTeacherRes'
  option.value.isBm = routeParam.client === 'bmBmTask' || routeParam.client === 'bmTeacherRes'
  option.value.isJs = routeParam.client === 'teacherRes' || routeParam.client === 'teacherTask'

  let isOk = checkRouteParam();

  if (isOk) {
    searchData()
  }

})

function selectionChange(rows) {
  option.value.selectIds = rows.map(item => item.id);
  option.value.selectNames = rows.map(item => item.name);
}

//搜索数据
function searchData() {
  option.value.loading = true;
  searchForm.value.startTime = dateToStr(searchForm.value.time[0])
  searchForm.value.endTime = dateToStr(searchForm.value.time[1])
  searchForm.value.type = route.query.type

  //教师和部门，只能查看已开启的任务
  if (option.value.isJs || option.value.isBm) {
    searchForm.value.isOpen = '0'
  }

  if (option.value.isJs) {
    jsPageTask(searchForm.value).then(res => {
      searchReturnRes(res)
    })
  }

  if (option.value.isBm) {
    bmPageTask(searchForm.value).then(res => {
      searchReturnRes(res)
    })
  }

  if (option.value.isJw) {
    jwPageTask(searchForm.value).then(res => {
      searchReturnRes(res)
    })
  }

}

//搜索数据
function searchReturnRes(res) {
  let {totalRow, records, pageNumber, pageSize} = res.data;
  option.value.loading = false;
  option.value.totalRow = totalRow * 1
  option.value.tableData = records
  searchForm.value.pageNumber = pageNumber * 1
  searchForm.value.pageSize = pageSize * 1
}

// 打开新增
function openAdd() {
  resetForm()
  option.value.dialogTitle = "新增任务";
  option.value.openDialog = true;
  option.value.dialogType = "add";
}

// 打开编辑
function openEdit(row) {
  //console.log(row)
  option.value.dialogTitle = "编辑任务";
  option.value.openDialog = true;
  option.value.dialogType = "edit";
  formData.value = copyNew(row);
}

// 打开编辑
function openFiles(row) {
  let dJsName = row.jsName ? "-" + row.jsName : ''
  let dKcName = row.kcName ? "-" + row.kcName : ''
  option.value.dialogFileTitle = "资料管理" + dJsName + dKcName;

  option.value.openFileDialog = true;
  option.value.dialogType = "file";
  option.value.taskId = row.id;
  formData.value = copyNew(row);
}

function submitAdd() {
  proxy.$refs["formDataRef"].validate(valid => {
    if (valid) {
      let param = copyNew(formData.value);
      param.startTime = dateToStr(param.startTime)
      param.endTime = dateToStr(param.endTime)
      param.type = route.query.type
      jwAddTask(param).then(res => {
        if (res.success) {
          //console.log(res)
          $modal.success();
          option.value.openDialog = false;
          searchData()
        }
      })
    }

  });
}

function submitEdit() {
  proxy.$refs["formDataRef"].validate(valid => {
    if (valid) {
      let param = copyNew(formData.value);
      param.startTime = dateToStr(param.startTime)
      param.endTime = dateToStr(param.endTime)
      param.type = route.query.type
      jwUpdateTask(param).then(res => {
        if (res.success) {
          //console.log(res)
          $modal.success();
          option.value.openDialog = false;
          searchData()
        }
      })

    }
  });
}

// 批量开启
function openBatch() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }
  //console.log(ids)
  let content = `正在开启名称为【 ${option.value.selectNames.join("、")}】 的任务，是否确定开启？ `
  $modal.confirmWarning(content)
      .then(async () => {
        let param = {ids: option.value.selectIds.join(","), isOpen: '0'}

        jwUpdateTaskStatus(param).then(res => {
          if (res.success) {
            $modal.success();
            searchData()
          }
        })

      }).catch(() => $modal.cancel());
}

// 批量关闭
function closeBatch() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }
  //console.log(ids)
  let content = `正在关闭名称为【 ${option.value.selectNames.join("、")}】 的数据项，是否确定关闭？ `
  $modal.confirmWarning(content)
      .then(async () => {
        let param = {ids: option.value.selectIds.join(","), isOpen: '1'}

        jwUpdateTaskStatus(param).then(res => {
          if (res.success) {
            $modal.success();
            searchData()
          }
        })

      }).catch(() => $modal.cancel());
}

// 批量删除
function deleteBatch() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }
  //console.log(ids)
  let content = `正在删除名称为【 ${option.value.selectNames.join("、")}】 的数据项，是否确定删除？ `
  $modal.confirmWarning(content)
      .then(async () => {
        let param = {ids: option.value.selectIds.join(",")}

        jwDelTask(param).then(res => {
          if (res.success) {
            $modal.success();
            searchData()
          }
        })

      }).catch(() => $modal.cancel());
}

//打开管理页面
function openZipManage(row) {
  //额外检查(teacherRes，必须等于99)
  if (option.value.isJw && route.path == '/jwBmTask') {
    option.value.dialogTitleZip = "部门任务-压缩包管理";
  } else if (option.value.isJw && route.path == '/jwTeacherTask') {
    option.value.dialogTitleZip = "教师任务-压缩包管理";
  } else {
    return;
  }
  option.value.openDialogZip = true;
  option.value.dialogTypeZip = "zip";
}

//批量生成压缩包
function createZipBatch() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }
  let title = "";
  let taskType = "";

  if (option.value.isJw && route.path == '/jwTeacherTask') {
    taskType = '0';
    title = "教师任务压缩包-" + dateToStr(new Date(), "yyyyMMdd-HHmmss");
  } else if (option.value.isJw && route.path == '/jwBmTask') {
    taskType = '1';
    title = "部门任务压缩包-" + dateToStr(new Date(), "yyyyMMdd-HHmmss");
  }

  ElMessageBox.prompt("如有需要，请自行修改输入框内的压缩包名称，无要求默认即可。", "批量生成压缩包", {
    inputPlaceholder: '请输入压缩包名称',
    inputValue: title,
    confirmButtonText: '立即生成',
    cancelButtonText: '取消',
    type: "warning",
  }).then(({value}) => {
    let zipName = trimStr(value)
    if (zipName.length === 0) {
      $modal.warning("压缩包名称不能为空");
      return;
    }

    loading("正在生成数据，请稍候...")

    let param = {
      zipName: zipName,
      taskType: taskType,
      taskIds: option.value.selectIds.join(","),
    }
    //教务处生成
    jwCreateTaskZip(param).then((res) => {
      closeLoading();
      if (res.success) {
        openToManage()
        $event.emit("searchMsg", {})
      }
    })

  }).catch((c) => {
    $modal.cancel();
  })

}

//打包成功，提示前往管理页面
function openToManage() {
  return ElMessageBox.confirm("压缩包正在生成中。 点击“压缩包管理”按钮，前往查看压缩包生成状态。", "系统提示", {
    confirmButtonText: '压缩包管理',
    cancelButtonText: '关闭',
    type: "success",
  }).then((res) => {
    openZipManage()
  }).catch((c) => {
  })
}

function checkRouteParam() {
  console.log(route)
  console.log(routeParam)
  let isOk = (routeParam.type && routeParam.client) && ('/' + routeParam.client === route.path)

  //额外检查(teacherRes，必须等于99)
  if (route.path == '/teacherRes' && routeParam.type != '99') isOk = false;

  //额外检查(bmTeacherRes，必须等于99)
  if (route.path == '/bmTeacherRes' && routeParam.type != '99') isOk = false;

  //额外检查(jwTeacherRes，必须等于99)
  if (route.path == '/jwTeacherRes' && routeParam.type != '99') isOk = false;

  //额外检查(bmBmTask，必须等于1)
  if (route.path == '/teacherTask' && routeParam.type != '0') isOk = false;

  //额外检查(bmBmTask，必须等于1)
  if (route.path == '/bmBmTask' && routeParam.type != '1') isOk = false;

  //额外检查(jwBmTask，必须等于1)
  if (route.path == '/jwBmTask' && routeParam.type != '1') isOk = false;

  //额外检查(jwTeacherTask，必须等于0)
  if (route.path == '/jwTeacherTask' && routeParam.type != '0') isOk = false;

  if (!isOk) {
    $modal.error("您访问的地址错误，请 点击【菜单/选项卡】进入页面；正在重定向至首页。");
    setTimeout(() => {
      router.push("/index").then(() => {
        window.location.reload()
      })
    }, 2000)
  }
  return isOk;
}

// 打开编辑
function downloadZip(row) {
  let param = {
    zipName: row.name + '.zip',
    taskIds: [row.id].join(","),
    type: '1'
  }
  loading("正在下载数据，请稍候...")
  if (option.value.isJw) {
    jwDownloadZip(param).then((data) => {
      saveAs(new Blob([data]), param.zipName);
      closeLoading();
    })

  }

}

//
function downloadBatch() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }
  loading("正在下载数据，请稍候...")

  //console.log(ids)
  let content = `正在执行批量下载操作，下载中途不能切换页面，是否继续执行？ `
  $modal.confirmWarning(content)
      .then(async () => {
        let param = {
          zipName: '批量下载压缩包.zip',
          taskIds: option.value.selectIds.join(","),
          type: '2'
        }
        if (option.value.isJw) {
          jwDownloadZip(param).then((data) => {
            param.zipName = '教务任务资料.zip'
            saveAs(new Blob([data]), param.zipName);
            closeLoading();
          })
        }

      }).catch(() => {
        $modal.cancel()
        closeLoading()
      }
  );

}

</script>

<style scoped lang="less">

</style>